package com.apes.project.jekunAuto.timeTask.crm.callCenter;


import com.alibaba.fastjson.JSONArray;
import com.apes.crm.callCenter.model.CustomComplain;
import com.apes.crm.callCenter.repository.CustomComplainRepository;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.MapUtil;
import com.apes.project.jekunAuto.timeTask.BaseService;
import com.apes.scm.rbac.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service("callCenterAutoService")
public class callCenterAutoService extends BaseService {
    @Autowired
    EntityManager entityManager;
    @Autowired
    CustomComplainRepository customComplainRepository;
    @Autowired
    UserRepository userRepository;

    public JSONArray restartComplainData() {
        Calendar calendar=Calendar.getInstance();
        calendar.setTime(new Date());
        int currentHour = calendar.get(Calendar.HOUR_OF_DAY);
        if( currentHour >= 18  || currentHour < 9) return new JSONArray(); //早9点到晚6点为启单日期
        List<CustomComplain> customComplainList = customComplainRepository.findCustomComplainRestart();

        JSONArray jsonArray = new JSONArray();
        customComplainList.stream().forEach( item ->  jsonArray.add(MapUtil.mapped(item)));
        return jsonArray;
    }

    public void restartComplainMethod(SimpleRequest request) {

        CustomComplain customComplain = customComplainRepository.findOne((String) request.get("id"));

        boolean isSuspend = this.invoke("wf.isProcessInstanceSuspend", MapUtil.mapper("innerBusinessType", customComplain.getInnerBusinessType(),
                "innerBusinessKey", customComplain.getInnerBusinessKey()));

        if (isSuspend) this.invoke("wf.activate", MapUtil.mapper("innerBusinessType", customComplain.getInnerBusinessType(),
                "innerBusinessKey", customComplain.getInnerBusinessKey()));

        customComplain.setStartId(userRepository.findOne(1).getPerson());
        customComplain.setRealStartDate(new Date());
        customComplain.setActive(true);
        customComplainRepository.saveAndFlush(customComplain);
    }



}
